package com.jushu.storbox;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jushu.storbox.actions.ActionShare;
import com.jushu.storbox.actions.ThumbnailAction;
import com.jushu.storbox.adapter.ActionShowSharedFriendsAdapter;
import com.jushu.storbox.callback.OnViewClickListener;
import com.jushu.storbox.callback.ShareListOperation;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.IntentConstant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.entities.SharedUser;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.ShareShipsRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.INodeShareV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.ShareResourceV2;
import com.huawei.sharedrive.sdk.android.serviceV2.ShareClientV2;

public class ActionShareActivity extends BaseTitleActivity implements ShareListOperation, OnViewClickListener<SharedUser> {

	private static final String LOG_TAG = ActionShareActivity.class.getSimpleName();

	public final static int SUCCESS_GET_SHARED_FRIENDS = 0x100001;

	private FileFolderInfo mInfo;
	private String iconPath;

	private ListView friendsList;
	private TextView friendsRecepit;
	private ImageView itemIcon;
	private TextView itemName;
	private TextView itemDate;
	private TextView cleanAllShareShip;

	private List<SharedUser> shareADuserList = new ArrayList<SharedUser>();
	private ActionShowSharedFriendsAdapter shareFileUserAdapter = null;

	private int resultCode = IntentConstant.INTENT_RESPONSE_MYSHARE_UNKNOW;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_action_share);
		// init data
		Intent intent = getIntent();
		mInfo = (FileFolderInfo) intent.getSerializableExtra(IntentConstant.INTENT_SHARE_DATA);

		// init title
		switchTypeOne();
		setCurrentRightIcon(R.mipmap.ic_menu_share_add);
		setCurrentTitle(this.getString(R.string.nav_save_txt));// should to
																// string

		// init content view
		itemIcon = (ImageView) findViewById(R.id.item_type_img);
		itemName = (TextView) findViewById(R.id.item_name_text);
		itemDate = (TextView) findViewById(R.id.item_date_text);
		friendsRecepit = (TextView) findViewById(R.id.share_friends_recepit);
		friendsList = (ListView) findViewById(R.id.share_friends_info);
		cleanAllShareShip = (TextView) findViewById(R.id.share_friends_clean_all);

		cleanAllShareShip.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// cancel all share
				final ClouddriveDialog delete = new ClouddriveDialog(ActionShareActivity.this, R.style.dialog_upload, R.layout.dialog_filedelete);
				View conventView = delete.getConventView();
				WindowManager windowManager=ActionShareActivity.this.getWindowManager();
				Display display=windowManager.getDefaultDisplay();
				delete.setWidth(display.getWidth());
				delete.setPosition(Gravity.CENTER_HORIZONTAL, Gravity.CENTER_VERTICAL);
				Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
				Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);

				TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
				dialog_prompt_tv.setText(R.string.action_share_promit_cancel_share);
				dialog_cancal.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						delete.dismiss();
					}
				});

				dialog_OK.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						delete.dismiss();
						new ActionShare().deleteAllShareShips(ActionShareActivity.this, handler, mInfo.getOwnerId(), mInfo.getId());
					}
				});
				delete.show();
			}
		});

		friendsRecepit.setText(formatRecepit());
		if (mInfo != null) {
			itemName.setText(mInfo.getName());
			itemDate.setText(formatDate());
			itemIcon.setImageResource(getTypeImgeID());
		}

		shareFileUserAdapter = new ActionShowSharedFriendsAdapter(getContext(), 0, shareADuserList);
		friendsList.setAdapter(shareFileUserAdapter);

	}

	@Override
	protected void onResume() {
		new GetShareUserAsyncTask(mInfo, handler).execute();
		super.onResume();
	}

	private String formatRecepit() {

		String str = getResources().getString(R.string.share_friends_count_info);
		String strReturn = getResources().getString(R.string.nav_save_txt);

		if (shareADuserList.size() > 0) {
			strReturn = String.format(str, shareADuserList.size());
		}
		return strReturn;
	}

	private Context getContext() {
		return ActionShareActivity.this;
	}

	@Override
	protected void onLeftClicked(View clickView) {
		super.onLeftClicked(clickView);
		Intent intent = new Intent();
		intent.putExtra(IntentConstant.INTENT_SHARE_DATA, mInfo);
		setResult(resultCode, intent);
		finish();
	}

	@Override
	protected void onRightClicked(View clickView) {
		Intent searchFriendIntent = new Intent();
		searchFriendIntent.setClass(getBaseContext(), ActionSearchShareFriendsActivity.class);
		searchFriendIntent.putExtra(IntentConstant.INTENT_SEARCH_FRIENDS_DATA, mInfo);
		startActivityForResult(searchFriendIntent, IntentConstant.INTENT_REQUEST_SEARCH_FRIENDS);
	}

	private void loadImagIcon() {
		try {
			iconPath = DirectoryUtil.genThumbnailFileFullName(getBaseContext(), mInfo.getOwnerBy(), mInfo.getId(), mInfo.getName());
			File thumBnail2 = new File(iconPath);
			if (!thumBnail2.exists()) {
				new ThumbnailAction().downloadThumbnailIcon(getBaseContext(), mInfo.getOwnerBy(), mInfo.getId(), iconPath, handler);
			} else {
				Message msg_download = new Message();
				msg_download.what = MessageCode.REQUEST_THUMBNAIL_INLOCAL;
				handler.sendMessage(msg_download);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e(TAG, "[getTypeImgeID] fileType is image that show fail..." + e.getLocalizedMessage());
		}
	}

	private String formatDate() {
		SimpleDateFormat timeDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		return timeDateFormat.format(mInfo.getModifiedAt());
	}

	private int getTypeImgeID() {
		// LogUtil.i(TAG, "getTypeImgeID...");
		int typeImgResId = R.mipmap.default_file_icon;
		if (mInfo.getIsFile() == FileType.File.value()) {
			if (PublicTools.isFileType(mInfo.getName(), Constant.WORD_TYPE)) {
				typeImgResId = R.mipmap.doc;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.PPT_TYPE)) {
				typeImgResId = R.mipmap.ppt;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.IMAGE_TYPE)) {
				typeImgResId = R.mipmap.empty_pic;
				loadImagIcon();
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.RAR_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.ZIP_TYPE)) {
				typeImgResId = R.mipmap.rar;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.VIDEO_TYPE)) {
				typeImgResId = R.mipmap.video;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.MUSIC_TYPE)) {
				typeImgResId = R.mipmap.music;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.TXT_TYPE)) {
				typeImgResId = R.mipmap.txt;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.PDF_TYPE)) {
				typeImgResId = R.mipmap.pdf;
			} else if (PublicTools.isFileType(mInfo.getName(), Constant.EXCEL_TYPE)) {
				typeImgResId = R.mipmap.excel;
			} else {
				typeImgResId = R.mipmap.default_file_icon;
			}
		} else {
			typeImgResId = R.mipmap.folder_im;
		}
		return typeImgResId;
	}

	ClientExceptionRelateHandler handler = new ClientExceptionRelateHandler() {
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MessageCode.REQUEST_THUMBNAIL_INLOCAL:
				new Thread(new Runnable() {
					public void run() {
						LogUtil.i(TAG, "thumb path: " + iconPath);
						Bitmap bmp = BitmapFactory.decodeFile(iconPath);
						ShareDriveApplication.getInstance().addCloudBitmaps(bmp);
						Message message = new Message();
						message.what = UiConstant.UPDATE_TYPE_ICON;
						message.obj = bmp;
						handler.sendMessage(message);
					}
				}).start();
				break;

			case UiConstant.UPDATE_TYPE_ICON:// refresh image ui
				Bitmap bmp = (Bitmap) msg.obj;
				if (null != bmp) {
					itemIcon.setImageBitmap(bmp);
				} else {
					LogUtil.e(TAG, "bitmap is null, show default img...");
				}
				break;

			case SUCCESS_GET_SHARED_FRIENDS:
				if (shareFileUserAdapter.getCount() == 0) {
					resultCode = IntentConstant.INTENT_RESPONSE_MYSHARE_CANCELED;
				} else {
					resultCode = IntentConstant.INTENT_RESPONSE_MYSHARE;
				}
				shareFileUserAdapter.notifyDataSetChanged();
				friendsRecepit.setText(formatRecepit());
				break;

			case UiConstant.SHARE_ACTION_DELETE_SHARE_SHIPS_SUCCESS:
				SharedUser user = (SharedUser) msg.obj;
				shareADuserList.remove(user);
				if (shareFileUserAdapter != null) {
					shareFileUserAdapter.notifyDataSetChanged();
				}
				friendsRecepit.setText(formatRecepit());
				if (shareFileUserAdapter.getCount() == 0) {
					resultCode = IntentConstant.INTENT_RESPONSE_MYSHARE_CANCELED;
				} else {
					resultCode = IntentConstant.INTENT_RESPONSE_MYSHARE;
				}
				break;
			case UiConstant.SHARE_ACTION_DELETE_ALL_SHARE_SHIPS_SUCCESS:
				new GetShareUserAsyncTask(mInfo, handler).execute();
				break;
			default:
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return getBaseContext();
		}
	};

	public class GetShareUserAsyncTask extends AsyncTask<FileFolderInfo, Integer, List<INodeShareV2>> {

		private FileFolderInfo fileFolderInfomation = null;

		private Handler resultHandlder = null;

		public GetShareUserAsyncTask(FileFolderInfo fileFolderInfo, Handler resultHandlder) {
			if (fileFolderInfo == null) {
				throw new IllegalArgumentException("FileFolderInfo instance is null");
			}
			this.fileFolderInfomation = fileFolderInfo;

			this.resultHandlder = resultHandlder;
		}

		protected List<INodeShareV2> doInBackground(FileFolderInfo... arg0) {
			List<INodeShareV2> listSharedUser = null;
			try {
				LogUtil.i(LOG_TAG, "get list share user data...");
				ShareShipsRequestV2 request = new ShareShipsRequestV2();
				request.setOwnerID(fileFolderInfomation.getOwnerBy());
				request.setNodeId(fileFolderInfomation.getId());
				ShareResourceV2 response = ShareClientV2.getInstance().listShareShips(ShareDriveApplication.getInstance().getAuthorization(), request);
				listSharedUser = response.getContents();
			} catch (ClientException e) {
				LogUtil.e(LOG_TAG, "[listSharedUser]code:" + e.getCode() + " | message:" + e.getLocalizedMessage());
				if (resultHandlder != null) {
					Message msg = resultHandlder.obtainMessage(ClientExceptionRelateHandler.CLIENT_EXCEPTION_OCCURED, e);
					msg.sendToTarget();
				} else {
					LogUtil.e(LOG_TAG, "resultHandlder is null");
				}
			}
			return listSharedUser;
		}

		protected void onPostExecute(List<INodeShareV2> SharedUserList) {
			if (SharedUserList != null) {
				// ArrayList<SharedUser> shareADuserList = new
				// ArrayList<SharedUser>();
				shareADuserList.clear();
				for (INodeShareV2 inodeShare : SharedUserList) {
					SharedUser sharedUser = new SharedUser();
					sharedUser.setShareStruts(true);
					sharedUser.setiNodeId(inodeShare.getNodeId());
					sharedUser.setModifiedAt(inodeShare.getModifiedAt());
					sharedUser.setName(inodeShare.getName());
					sharedUser.setSharedDepartment(inodeShare.getSharedUserDescription());
					sharedUser.setSharedUserLoginName(inodeShare.getSharedUserLoginName());
					sharedUser.setSharedUserName(inodeShare.getSharedUserName());
					sharedUser.setSharedUserId(inodeShare.getSharedUserId());
					sharedUser.setSharedUserType(inodeShare.getSharedUserType());
					shareADuserList.add(sharedUser);
				}

				resultHandlder.obtainMessage(SUCCESS_GET_SHARED_FRIENDS).sendToTarget();

				if (shareFileUserAdapter != null) {
					shareFileUserAdapter.notifyDataSetChanged();
				}
			}
		}

	}

	@Override
	public void shareListOperating(int id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.putExtra(IntentConstant.INTENT_SHARE_DATA, mInfo);
		setResult(resultCode, intent);
		finish();
		super.onBackPressed();
	}

	public void onViewClick(View view, SharedUser data) {
		switch (view.getId()) {
		case R.id.shared_friends_delete:
			new ActionShare().deleteShareShips(getBaseContext(), data, mInfo.getOwnerBy(), handler);
			break;

		}
	}

}
